package cn.woniu.ecommerceplatform.service.impl;

import cn.woniu.ecommerceplatform.util.ResponseResult;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.woniu.ecommerceplatform.entity.Goods;
import cn.woniu.ecommerceplatform.service.GoodsService;
import cn.woniu.ecommerceplatform.mapper.GoodsMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
* @author QIQI
* &#064;description  针对表【t_goods】的数据库操作Service实现
* &#064;createDate  2023-01-05 12:21:22
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods>
    implements GoodsService{
    @Autowired(required = false)
    private GoodsMapper goodsMapper;
    @Value("${imgPath.path}")
    private String imgPath;
    @Override
    public ResponseResult<?> goodsDelete(Integer[] ids) {

        List<Integer> idlist = new ArrayList<>(Arrays.asList(ids));
        try {
            List<Goods> goods = goodsMapper.queryGoodByIds(idlist);
            goods.forEach(good ->{
                deleteGoodImg(good);
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
        int count = goodsMapper.deleteBatchIds(idlist);

        if (count>0) {
            return new ResponseResult<>().deleteSuccess((long) count);
        }else{
            return new ResponseResult<>().notok();
        }

    }

    private void deleteGoodImg(Goods good) {
        String goodImg = good.getGoodImg();
        File dir = new File(imgPath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        String dirPath = dir.getAbsolutePath();
        if(goodImg != null) {
            String imgName = goodImg.substring(goodImg.lastIndexOf("/") + 1);
            File file = new File(dirPath+File.separator + imgName);
            if (file.exists()) {
                file.delete();
            }
        }
    }

    @Override
    public ResponseResult<?> goodUpdate(Goods goods) {
        Goods goods1 = goodsMapper.queryGoodById(goods.getId());
        String goodImg = goods1.getGoodImg();
        File dir = new File(imgPath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        String dirPath = dir.getAbsolutePath();
        if(goodImg!=null){
            if(!goodImg.equals(goods.getGoodImg())){
                String imgName = goodImg.substring(goodImg.lastIndexOf("/") + 1);
                File file=new File(dirPath+File.separator+imgName);
                if(file.exists()){
                    file.delete();
                }
            }
        }
        if(goods.getIsPointGoods()==1){
            goods.setPointPrice(goods.getGoodPrice().multiply(BigDecimal.valueOf(15.00)));
        }
        int count = goodsMapper.updateById(goods);
        if(count>0){
            return new ResponseResult<>().ok();
        }else {
            return new ResponseResult<>().notok();
        }
    }

    @Override
    public ResponseResult<?> goodDelete(Integer id) {
        Goods goods = goodsMapper.queryGoodById(id);
        int count = goodsMapper.deleteById(id);
        deleteGoodImg(goods);
        if(count>0){
            return new ResponseResult<>().deleteSuccess((long) count);
        }else {
            return new ResponseResult<>().notok();
        }
    }

    @Override
    public ResponseResult<?> goodAdd(Goods goods) {
        try {
            goods.setCreateTime(new Date());
            if(goods.getIsPointGoods()==1){
                goods.setPointPrice(goods.getGoodPrice().multiply(BigDecimal.valueOf(15.00)));
            }
            int count = goodsMapper.insert(goods);
            if(count>0){
                return new ResponseResult<>().ok();
            }else{
                return new ResponseResult<>().notok();
            }
        } catch (Exception e) {
            return new ResponseResult<>().notok("请完善信息后，再进行添加");
        }
    }

    @Override
    public ResponseResult<?> goodsList(String goodName,String goodCode, Integer shelfStatus,Integer pageNum ,Integer pageSize) {
        try {
            List<Goods> goods;
            PageInfo<Goods> goodsPageInfo;
            if(pageNum!=null && pageSize!=null) {
                PageHelper.startPage(pageNum, pageSize);
                goods = goodsMapper.queryBygoodNameOrgoodCodeOrshelfStatus(goodName, goodCode, shelfStatus);
                goodsPageInfo = new PageInfo<>(goods);
                if (!(goodsPageInfo.getSize() > 0) && pageNum > 1) {
                    PageHelper.startPage(pageNum - 1, pageSize);
                    goods = goodsMapper.queryBygoodNameOrgoodCodeOrshelfStatus(goodName, goodCode, shelfStatus);
                    goodsPageInfo = new PageInfo<>(goods);
                }
            }else {
                goods=goodsMapper.queryBygoodNameOrgoodCodeOrshelfStatus(goodName,goodCode,shelfStatus);
                goodsPageInfo=new PageInfo<>(goods);
            }
            if(goods.isEmpty()){
                return new ResponseResult<>().isNull();
            }else {
                return new ResponseResult<>().ok(goodsPageInfo);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public ResponseResult<?> deleteShelf(Integer[] ids) {
        return updateShelf(0, Arrays.asList(ids));
    }

    @Override
    public ResponseResult<?> queryGoods(String goodName, Integer typeId, Integer pageNum, Integer pageSize) {
        try {
            List<Goods> goods;
            PageInfo<Goods> goodsPageInfo;
            if(pageNum!=null && pageSize!=null) {
                PageHelper.startPage(pageNum, pageSize);
                goods = goodsMapper.queryBygoodNameOrtypeId(goodName,typeId);
                goodsPageInfo = new PageInfo<>(goods);
                if (!(goodsPageInfo.getSize() > 0) && pageNum > 1) {
                    PageHelper.startPage(pageNum - 1, pageSize);
                    goods = goodsMapper.queryBygoodNameOrtypeId(goodName,typeId);
                    goodsPageInfo = new PageInfo<>(goods);
                }
            }else {
                goods=goodsMapper.queryBygoodNameOrtypeId(goodName,typeId);
                goodsPageInfo=new PageInfo<>(goods);
            }
            if(goods.isEmpty()){
                return new ResponseResult<>().isNull();
            }else {
                return new ResponseResult<>().ok(goodsPageInfo);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    public ResponseResult<?> queryPG(String goodName, Integer pageNum,Integer pageSize) {
        try {
            List<Goods> goods;
            PageInfo<Goods> goodsPageInfo;
            if(pageNum!=null && pageSize!=null) {
                PageHelper.startPage(pageNum, pageSize);
                goods = goodsMapper.queryPGByNameCodeShelfStatus(goodName);
                goodsPageInfo = new PageInfo<>(goods);
                if (!(goodsPageInfo.getSize() > 0) && pageNum > 1) {
                    PageHelper.startPage(pageNum - 1, pageSize);
                    goods = goodsMapper.queryPGByNameCodeShelfStatus(goodName);
                    goodsPageInfo = new PageInfo<>(goods);
                }
            }else {
                goods=goodsMapper.queryPGByNameCodeShelfStatus(goodName);
                goodsPageInfo=new PageInfo<>(goods);
            }
            if(goods.isEmpty()){
                return new ResponseResult<>().isNull();
            }else {
                return new ResponseResult<>().ok(goodsPageInfo);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public ResponseResult<?> queryGoodById(Integer id) {
        Goods goods = goodsMapper.queryGoodById(id);
        if (goods!=null){
            return new ResponseResult<>().ok(goods);
        } else {
            return new ResponseResult<>().notok();
        }

    }

    @Override
    public ResponseResult<?> addShelf(Integer[] ids) {
        return updateShelf(1, Arrays.asList(ids));
    }

    /**
     * 根据商品id批量修改商品在架状态
     * @param shelfStatus 要修改的商品状态
     * @param ids 商品id集合
     * @return 所需返回信息
     */
    private ResponseResult<?> updateShelf(Integer shelfStatus,List<Integer> ids) {
        Integer count = null;
        try {
            List<Integer> idList=new ArrayList<>(ids);
            /**
             * 0=下架
             * 1=上架
             */
            count = goodsMapper.UpdateShelfStatusByids(idList,shelfStatus);
        } catch (Exception e) {
            return ResponseResult.ServerException;
        }
        if(count>0){
            return new ResponseResult<>().ok(null,"成功修改了"+count+"条数据");
        }else {
            return new ResponseResult<>().notok();
        }
    }


}




